﻿// /////////////////////////////////////////////////////////////////////
// 
//  Codeplex JSAnalyse
//  Copyright (c) 2011
//  JSAnalyse.ConsoleApp   Program.cs
// 
// /////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.IO;
using JSAnalyse.Core;

namespace JSAnalyse.ConsoleApp
{
    /// <summary>
    /// Console Application to check JS dependencies
    /// </summary>
    public class Program
    {
        private static int Main(string[] args)
        {
            // todo:create unit test with test files
            if (args.Length == 0)
            {
                Console.Error.WriteLine(
                    "ERROR: Please pass the javascript files which should be analysed.\n\nExample:\nJSAnalyse <path>\\*.js");
                return 1;
            }

            IEnumerable<string> filesToProcess = GetFilesToProcess(args);

            bool errorOccured = false;

            List<DependencyRunnerResult> result = new DependencyRunner(filesToProcess).Start();
            foreach (DependencyRunnerResult item in result)
            {
                foreach (DependencyInfo wrongDependency in item.WrongFileDependencies)
                {
                    errorOccured = true;
                    string message =
                        string.Format("File {0} has wrong Dependency to File {1} in Line {2}, Character {3}\nSource: {4}",
                                      item.SourceFile, 
                                      wrongDependency.File, 
                                      wrongDependency.DependencySourceLocation.Line,
                                      wrongDependency.DependencySourceLocation.Character,
                                      wrongDependency.DependencySourceLocation.SourceLine);
                    Console.Error.WriteLine(message);
                }
            }

            if (errorOccured)
            {
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// Gets the files to process from given args collection 
        /// </summary>
        /// <param name="args">The args collection with file pathes</param>
        /// <returns>absolute file pathes found</returns>
        private static IEnumerable<string> GetFilesToProcess(IEnumerable<string> args)
        {
            var result = new List<string>();
            foreach (string arg in args)
            {
                string path = Path.GetDirectoryName(arg) ?? string.Empty;
                string fileNamePattern = Path.GetFileName(arg) ?? string.Empty;
                result.AddRange(Directory.GetFiles(path, fileNamePattern));
            }
            return result;
        }
    }
}